package models;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.CheckSpeed;

public class CheckSpeedModel {
private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "checkspeed_";
	
	private static CheckSpeedModel instance = null;
	
	public static CheckSpeedModel getInstance() {
		if (instance == null) {
			instance = new CheckSpeedModel();
		}
		
		return instance;
	}
	
	private CheckSpeedModel() {
		try {
			ObjectifyService.register(CheckSpeed.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		/*try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }*/
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<CheckSpeed> list(int page, int limit) {
		ArrayList<CheckSpeed> checkSpeeds = new ArrayList<CheckSpeed>();
		
		int start = (page - 1) * limit;
		Query<CheckSpeed> q = ofy.query(CheckSpeed.class).limit(limit).offset(start);
		for (CheckSpeed checkSpeed: q) {
			checkSpeeds.add(checkSpeed);
		}
		
		return checkSpeeds;
	}
	
	public void insert(CheckSpeed checkSpeed) {
		if (cache != null) {
			cache.put(prefix + checkSpeed.getDomain(), checkSpeed);
		}
		
		ofy.put(checkSpeed);
	}
	
	public void delete(CheckSpeed checkSpeed) {
		if (cache != null && cache.containsKey(prefix + checkSpeed.getDomain())) {
			cache.remove(prefix + checkSpeed.getDomain());
		}
		
		ofy.delete(checkSpeed);
	}
	
	public CheckSpeed get(String name) {
		CheckSpeed checkSpeed = new CheckSpeed();
		if (cache != null && cache.containsKey(prefix + name)) {
			
			checkSpeed = (CheckSpeed) cache.get(prefix + name);
		} else {
			try {
				checkSpeed = ofy.get(new Key<CheckSpeed>(CheckSpeed.class, name));
				if (cache != null) {
					cache.put(prefix + name, checkSpeed);
				}
			} catch (Exception e) {
				checkSpeed = null;
			}
		}
		return checkSpeed;
	}
}
